/*
 * @(#)ChainReceiverApplication.java
 * Date 2013-03-30
 * Version 1.0
 * Author Jim Horner
 * Copyright (c)2012
 */


package us.hornerscorners.lamppost.hapiservice;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import ca.uhn.hl7v2.HL7Exception;

import ca.uhn.hl7v2.model.Message;

import ca.uhn.hl7v2.protocol.ReceivingApplication;
import ca.uhn.hl7v2.protocol.ReceivingApplicationException;


/**
 *
 * @author jim
 */
public class ChainReceiverApplication implements ReceivingApplication {

    /** Field description */
    private final List<ReceivingApplication> listeningApplications;

    /** Field description */
    private final List<ReceivingApplication> receivingApplications;

    /**
     * Constructs ...
     *
     */
    public ChainReceiverApplication() {

        super();

        this.receivingApplications = new ArrayList<>();
        this.listeningApplications = new ArrayList<>();
    }

    /**
     * Method description
     *
     *
     * @param application
     */
    public void addApplication(ReceivingApplication application) {

        this.receivingApplications.add(application);
    }

    /**
     * Method description
     *
     *
     * @param listener
     */
    public void addListener(ReceivingApplication listener) {

        this.listeningApplications.add(listener);
    }

    /**
     * Method description
     *
     *
     * @param msg
     *
     * @return
     */
    @Override
    public boolean canProcess(Message msg) {

        boolean result = false;

        for (ReceivingApplication app : this.receivingApplications) {

            if (app.canProcess(msg)) {
                result = true;
                break;
            }
        }

        return result;
    }

    /**
     * Method description
     *
     *
     * @param msg
     * @param map
     *
     * @return
     *
     * @throws HL7Exception
     * @throws ReceivingApplicationException
     */
    @Override
    public Message processMessage(Message msg, Map<String, Object> map)
            throws ReceivingApplicationException, HL7Exception {

        Message result = null;

        for (ReceivingApplication listener : this.listeningApplications) {

            if (listener.canProcess(msg)) {

                result = listener.processMessage(msg, map);
                break;
            }
        }

        for (ReceivingApplication app : this.receivingApplications) {

            if (app.canProcess(msg)) {

                result = app.processMessage(msg, map);
                break;
            }
        }

        return result;
    }
}
